package com.bawei.module_home.search

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.R
import com.bawei.module_home.home.model.entity.VideoEntity
import com.bawei.module_home.home.model.repository.HomeRepository
import com.google.android.flexbox.FlexboxLayout
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class SearchActivity : AppCompatActivity() {
    
    private lateinit var etSearch: EditText
    private lateinit var btnBack: ImageView
    private lateinit var rvSearchResults: RecyclerView
    private lateinit var searchAdapter: SearchResultAdapter
    private lateinit var homeRepository: HomeRepository
    private lateinit var flexboxHistory: FlexboxLayout
    private lateinit var tvHistoryTitle: TextView
    private val mmkv by lazy { MMKV.defaultMMKV() }
    private val HISTORY_KEY = "search_history"
    private val MAX_HISTORY = 10
    
    private var allVideos = mutableListOf<VideoEntity>()
    private var searchJob: Job? = null
    private var channelId: String = "1"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        
        // 获取传递过来的channelId
        channelId = intent.getStringExtra("channelId") ?: "1"
        
        initViews()
        initRecyclerView()
        initRepository()
        setupListeners()
        loadVideoData()
        tvHistoryTitle = findViewById(R.id.tv_history_title)
        flexboxHistory = findViewById(R.id.flexbox_history)
        showSearchHistory()
    }
    
    private fun initViews() {
        etSearch = findViewById(R.id.et_search)
        btnBack = findViewById(R.id.btn_back)
        rvSearchResults = findViewById(R.id.rv_search_results)
        // 移除跳转到商品搜索页面的点击事件，恢复本地搜索行为
        etSearch.isFocusable = true
        etSearch.isFocusableInTouchMode = true
        etSearch.setOnClickListener(null)
    }
    
    private fun initRecyclerView() {
        searchAdapter = SearchResultAdapter { video ->
            // 处理视频点击事件
            Toast.makeText(this, "点击了: ${video.title}", Toast.LENGTH_SHORT).show()
        }
        
        rvSearchResults.apply {
            layoutManager = LinearLayoutManager(this@SearchActivity)
            adapter = searchAdapter
        }
    }
    
    private fun initRepository() {
        homeRepository = HomeRepository()
    }
    
    private fun setupListeners() {
        btnBack.setOnClickListener {
            finish()
        }
        
        etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: Editable?) {
                searchJob?.cancel()
                val searchText = s?.toString()?.trim() ?: ""
                if (searchText.isEmpty()) {
                    // 搜索框为空时清空结果并显示历史
                    searchAdapter.updateData(emptyList())
                    showSearchHistory()
                    return
                }
                // 有内容时隐藏历史
                tvHistoryTitle.visibility = View.GONE
                flexboxHistory.visibility = View.GONE
                // 延迟500ms执行搜索，避免用户连续输入时频繁搜索
                searchJob = lifecycleScope.launch {
                    delay(500)
                    performSearch(searchText)
                }
            }
        })
    }
    
    private fun loadVideoData() {
        lifecycleScope.launch {
            try {
                // 用传递过来的channelId请求数据
                homeRepository.getVideo(channelId, 1, 100).collect { result ->
                    if (result.code == 200) { // 假设200是成功状态码
                        val videoList = result.data ?: emptyList()
                        allVideos.clear()
                        allVideos.addAll(videoList)
                        // 数据加载成功，但不显示，等待用户搜索
                       // Toast.makeText(this@SearchActivity, "数据加载完成，共${videoList.size}条数据，可以开始搜索", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@SearchActivity, "数据加载失败: ${result.msg}", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(this@SearchActivity, "网络请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun performSearch(searchText: String) {
        if (allVideos.isEmpty()) {
            Toast.makeText(this, "数据还未加载完成，请稍后再试", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 保存历史
        saveSearchHistory(searchText)
        
        // 在本地数据中搜索匹配的视频
        val filteredVideos = allVideos.filter { video ->
            video.title.contains(searchText, ignoreCase = true)
        }
        
        // 有输入内容时隐藏搜索历史
        tvHistoryTitle.visibility = View.GONE
        flexboxHistory.visibility = View.GONE
        if (filteredVideos.isEmpty()) {
            Toast.makeText(this, "暂未查找到您所查找的内容", Toast.LENGTH_SHORT).show()
            searchAdapter.updateData(emptyList())
        } else {
            searchAdapter.updateData(filteredVideos)
        }
    }
    
    private fun saveSearchHistory(keyword: String) {
        if (keyword.isBlank()) return
        val history = getSearchHistory().toMutableList()
        history.remove(keyword) // 去重
        history.add(0, keyword) // 新的放最前
        if (history.size > MAX_HISTORY) history.removeLast()
        mmkv.encode(HISTORY_KEY, history.joinToString("||"))
        showSearchHistory()
    }

    private fun getSearchHistory(): List<String> {
        val str = mmkv.decodeString(HISTORY_KEY, "") ?: ""
        return if (str.isBlank()) emptyList() else str.split("||")
    }

    private fun showSearchHistory() {
        val history = getSearchHistory()
        if (history.isEmpty()) {
            tvHistoryTitle.visibility = View.GONE
            flexboxHistory.visibility = View.GONE
            return
        }
        tvHistoryTitle.visibility = View.VISIBLE
        flexboxHistory.visibility = View.VISIBLE
        flexboxHistory.removeAllViews()
        history.forEach { keyword ->
            val tv = LayoutInflater.from(this).inflate(R.layout.item_search_history_tag, flexboxHistory, false) as TextView
            tv.text = keyword
            tv.setOnClickListener {
                etSearch.setText(keyword)
                etSearch.setSelection(keyword.length)
            }
            flexboxHistory.addView(tv)
        }
    }
}